package com.ruoyi.project.system.wxcontroller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.security.service.SysLoginService;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.Member;
import com.ruoyi.project.system.domain.Student;
import com.ruoyi.project.system.mapper.MemberMapper;
import com.ruoyi.project.system.mapper.StudentMapper;
import com.ruoyi.project.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.beans.Transient;
import java.util.Date;
import java.util.List;


/**
 * 微信登录Controller
 *
 * @author ruoyi
 * @date 2020-10-07
 */
@RestController
@RequestMapping("/api")
public class LoginController extends BaseController {

    private static final String APPID = "wxe47a0ca97f83ac52";

    private static final String SECRET = "f6e5c294953c4f191cdb6dc081986676";

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IWxLoginService wxLoginService;


    @Autowired
    private IStudentService studentService;

    @Autowired
    private ICollegeStaffService collegeStaffService;

    @Autowired
    private ISysUserService sysUserService;
   @Autowired
    private StudentMapper studentMapper;

   @Autowired
    private MemberMapper memberMapper;

    /**
     * 静默登录
     */
    @Transient
    @GetMapping("/openidLogin")
    public AjaxResult openidLogin(String code) {
        //微信的接口
        AjaxResult ajax = AjaxResult.success();
        String openid = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID +
                "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            JSONObject obj = JSON.parseObject(sessionData);
            //获取用户的唯一标识
            openid = obj.getString("openid");
        }
        //根据返回值进行后续操作
        if(openid != null){
            Member member = memberService.getByOpenid(openid);
            if(member != null){
                Long typeCode = member.getTypeCode();
                String username = null;
                String password = null;
                if(typeCode == 1){
                    Student student  = studentService.selectStudentByMemberId(member.getId());
                    username = student.getIdcardCode();
                    password = student.getRealName();
                }else if(typeCode == 2){
                    username = member.getCode();
                    password = member.getPwd();
                }else{
                    return AjaxResult.error("校管账号不允许登录!");
                }
                ajax.put(Constants.TOKEN, loginService.wxLogin(username, password,typeCode.intValue()));
                ajax.put("code", 200);
                ajax.put("userType", member.getTypeCode().intValue());

                return ajax;

            }else{
                ajax.put("code", 204);
                ajax.put("openid", openid);
                return ajax;
            }
        }else{
            return AjaxResult.error("系统出错，请联系管理员!");
        }

    }


    /**
     * 微信端登录
     *
     * @param authCode
     * @return
     */
    @Transient
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public AjaxResult login(String authCode) {
        AjaxResult ajax = AjaxResult.success();
        //微信的接口
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID +
                "&secret=" + SECRET + "&js_code=" + authCode + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            JSONObject obj = JSON.parseObject(sessionData);
            //获取用户的唯一标识
            String openid = obj.getString("openid");
            //获取用户的用户在开放平台的唯一标识符
            String unionid = obj.getString("unionid");
            //获取会话秘钥
            String session_key = obj.getString("session_key");
            //下面就可以写自己的业务代码了
            //最后要返回一个自定义的登录态,用来做后续数据传输的验证
            if(openid != null && !openid.equals("")){
                ajax.put("openid", openid);
                ajax.put("code", 200);
            }else{
                return AjaxResult.error("系统出错，请联系管理员!");
            }
            return ajax;
           /* SysUser user = memberService.getUserByOpenid(openid);
            if (user != null) {
                String token = loginService.wxLogin(user.getUserName(), user.getPw(),1);
                ajax.put("openid", openid);
                ajax.put("code", 200);
                ajax.put(Constants.TOKEN, token);
                return ajax;
            } else {
                ajax.put("openid", openid);
                ajax.put("isLogin", false);
                return ajax;
            }*/
        }
        return AjaxResult.error("系统出错，请联系管理员!");
    }


    /**
     * 通过账号密码登录，type=1为学生登录。username为身份证，password为姓名，type=2为老师登录，username，password不变
     *
     * @param username
     * @param password
     * @return
     */
    @Transient
    @GetMapping("/loginUser")
    public AjaxResult loginUser(String username, String password, int type,String openid,String userInfo) {
        String token = null;

        if(!openid.isEmpty() && openid!=null && userInfo != null){
            if(type==1){
                token = loginService.wxLogin(username, password,type);
                if(token!=null){
                    Member member = memberService.getByOpenid(openid);
                    Student student =  studentMapper.selectStudentByUserIdcard(username).get(0);
                    JSONObject obj = JSON.parseObject(userInfo);
                    if(member == null){
                        //生成会员表记录
                        Member member1 = new Member(){{
                            setWxOpenId(openid);
                            setWxAvatar(obj.getString("avatarUrl"));
                            setWxNick(obj.getString("nickName"));
                            setCreateDt(new Date());
                            setTypeCode((long) type);
                            setCellphone(student.getCellphone());
                        }};
                        int row = memberService.insertMember(member1);
                        if(row == 1){
                                studentService.updateMemberIdByIdCard(username,memberService.getByOpenid(openid).getId());
                        }
                    }
                }
            }else if(type==2){

                token = loginService.wxLogin(username, password,type);
                if(token!=null){
                    Member member = memberService.getByOpenid(openid);
                    if(member == null){
                        //老师则直接update生成会员表
                        JSONObject obj = JSON.parseObject(userInfo);
                        List<Member> memberInfo = memberMapper.setMemberList(username,password);
                        Member member1 = new Member(){{
                            setId(memberInfo.get(0).getId());
                            setWxOpenId(openid);
                            setWxAvatar(obj.getString("avatarUrl"));
                            setWxNick(obj.getString("nickName"));
                        }};
                        int row = memberService.updateMember(member1);

                    }
                }

            }

        }

        AjaxResult ajax = new AjaxResult();
        ajax.put(Constants.TOKEN, token);
        ajax.put("code", 200);
        return ajax;
    }

}
